package com.atguigu.demojuc.chap08;


import java.util.concurrent.*;


class Ticket{
    private int num = 20;


    public synchronized void sale(){
        if(num<0){
            System.out.println("票已售罄");
            return;
        }
        try {
            System.out.println((Thread.currentThread().getName() + "\t" + "开始售票：" + num));
            num--;
            Thread.sleep(200);
            System.out.println((Thread.currentThread().getName() + "\t" + "剩余票数：" + num));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }
}


public class SaleTicket_ThreadPoolExecutor {

    public static void main(String[] args) {

        Ticket ticket = new Ticket();


        ThreadPoolExecutor executor=new ThreadPoolExecutor(1,
                3,
                0,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        executor.submit(r);
                    }
                }
        );



        for (int i = 1; i <=20; i++) {
            String num = String.valueOf(i);
            Future<Integer> futureResult =executor.submit(()->{
                ticket.sale();
                return 100;
            });

//            try {
//                futureResult.get();
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            } catch (ExecutionException e) {
//                throw new RuntimeException(e);
//            }

        }
    }

}


